package com.fqgj.xjd.user.service.impl;

import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.exception.common.ApiErrorException;
import com.fqgj.xjd.user.client.UserFrozenService;
import com.fqgj.xjd.user.client.UserInfoService;
import com.fqgj.xjd.user.client.enums.OperateTypeEnum;
import com.fqgj.xjd.user.client.request.*;
import com.fqgj.xjd.user.client.response.User;
import com.fqgj.xjd.user.client.response.UserFrozen;
import com.fqgj.xjd.user.client.response.UserInfo;
import com.fqgj.xjd.user.client.response.UserResidentInfo;
import com.fqgj.xjd.user.common.enums.UserErrorCodeEnum;
import com.fqgj.xjd.user.dao.*;
import com.fqgj.xjd.user.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:
 * @Description: 用户登录服务
 * @Author zhangxingyun
 * @Create 2017-07-21 09:37
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private UserBaseDao userBaseDao;

    @Autowired
    private UserBaseContactDao userBaseContactDao;

    @Autowired
    private UserBaseResidentDao userBaseResidentDao;

    @Autowired
    private UserBaseWorkDao userBaseWorkDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserFrozenService userFrozenService;

    @Autowired
    private UserAccessDao userAccessDao;

    @Autowired
    private CityPinCodeDao cityPinCodeDao;

    @Autowired
    private UserOperateFlowDao userOperateFlowDao;

    @Autowired
    private UserPromotionStatsDao userPromotionStatsDao;

    /**
     * 创建基本信息--用户基本信息
     *
     * @param userBase
     * @return
     */
    @Override
    public Response<Boolean> addUserBase(UserBase userBase) {
        UserBaseEntity oldEntity = userBaseDao.selectByUserCode(userBase.getUserCode());
        if (oldEntity != null) {
            return updateUserBase(userBase);
        }
        UserBaseEntity entity = new UserBaseEntity();
        BeanUtils.copyProperties(userBase, entity);
        String firstName = StringUtils.isNotBlank(userBase.getFirstName()) ? userBase.getFirstName() : "";
        String lastName = StringUtils.isNotBlank(userBase.getLastName()) ? userBase.getLastName() : "";
        if (firstName.equalsIgnoreCase(lastName)) {
            entity.setFirstName(firstName);
            entity.setLastName("");
        }
        userBaseDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * 创建基本信息--联系方式
     *
     * @param userContact
     * @return
     */
    @Override
    public Response<Boolean> addUserContact(UserContact userContact) {
        UserBaseContactEntity oldEntity = userBaseContactDao.selectByUserCode(userContact.getUserCode());
        if (oldEntity != null) {
            return updateUserContact(userContact);
        }
        UserBaseContactEntity entity = new UserBaseContactEntity();
        BeanUtils.copyProperties(userContact, entity);
        userBaseContactDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * 创建基本信息--居住信息
     *
     * @param userResident
     * @return
     */
    @Override
    public Response<Boolean> addUserResident(UserResident userResident) {


        // 保存state/city信息
        if (StringUtils.isNotBlank(userResident.getPermanentPinCode())) {
            CityPinCodeEntity cityPinCodeEntity = cityPinCodeDao.selectStateCityByPinCode(userResident.getPermanentPinCode());
            if (cityPinCodeEntity != null) {
                userResident.setPermanentState(cityPinCodeEntity.getStatename());
                userResident.setPermanentCity(cityPinCodeEntity.getTaluk());
            }
        }
        if (StringUtils.isNotBlank(userResident.getPinCode())) {
            CityPinCodeEntity cityPinCodeEntity = cityPinCodeDao.selectStateCityByPinCode(userResident.getPinCode());
            if (cityPinCodeEntity != null) {
                userResident.setProvince(cityPinCodeEntity.getStatename());
                userResident.setCity(cityPinCodeEntity.getTaluk());
            }
        }
        UserBaseResidentEntity oldEntity = userBaseResidentDao.selectByUserCode(userResident.getUserCode());
        if (oldEntity != null) {
            return updateUserResident(userResident);
        }

        UserBaseResidentEntity entity = new UserBaseResidentEntity();
        BeanUtils.copyProperties(userResident, entity);


        userBaseResidentDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * 创建基本信息--工作信息
     *
     * @param userWork
     * @return
     */
    @Override
    public Response<Boolean> addUserWork(UserWork userWork) {
        UserBaseWorkEntity oldEntity = userBaseWorkDao.selectByUserCode(userWork.getUserCode());
        if (oldEntity != null) {
            return updateUserWork(userWork);
        }
        UserBaseWorkEntity entity = new UserBaseWorkEntity();
        BeanUtils.copyProperties(userWork, entity);

        // 保存state/city信息
        if (StringUtils.isNotBlank(userWork.getOfficePinCode())) {
            CityPinCodeEntity cityPinCodeEntity = cityPinCodeDao.selectStateCityByPinCode(userWork.getOfficePinCode());
            if (cityPinCodeEntity != null) {
                entity.setProvince(cityPinCodeEntity.getStatename());
                entity.setCity(cityPinCodeEntity.getTaluk());
            }
        }

        userBaseWorkDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * 更新基本信息--用户基本信息
     *
     * @param userBase
     * @return
     */
    @Override
    public Response<Boolean> updateUserBase(UserBase userBase) {
        if (StringUtils.isBlank(userBase.getUserCode())) {
            return Response.error(UserErrorCodeEnum.LOST_USER_ID);
        }
        UserBaseEntity entity = new UserBaseEntity();
        BeanUtils.copyProperties(userBase, entity);
        entity.setGmtModified(new Date());
        userBaseDao.updateByUserCode(entity);

        // 更新user表
        String firstName = StringUtils.isNotBlank(userBase.getFirstName()) ? userBase.getFirstName() : "";
        String lastName = StringUtils.isNotBlank(userBase.getLastName()) ? userBase.getLastName() : "";
        String userName;
        if (firstName.equalsIgnoreCase(lastName)) {
            userName = firstName;
        } else {
            userName = firstName + " " + lastName;
        }
        if (StringUtils.isBlank(userName)) {
            return Response.ok().putData(true);
        }

        UserEntity userEntity = userDao.selectByCustomerCode(userBase.getUserCode());
        if (userEntity == null || userEntity.getId() == null) {
            return Response.ok().putData(true);
        }
        userDao.updateUserName(userEntity.getId(), userName);

        return Response.ok().putData(true);
    }

    /**
     * 更新基本信息--联系方式
     *
     * @param userContact
     * @return
     */
    @Override
    public Response<Boolean> updateUserContact(UserContact userContact) {
        if (StringUtils.isBlank(userContact.getUserCode())) {
            return Response.error(UserErrorCodeEnum.LOST_USER_ID);
        }
        UserBaseContactEntity entity = new UserBaseContactEntity();
        BeanUtils.copyProperties(userContact, entity);
        entity.setGmtModified(new Date());
        userBaseContactDao.updateByUserCode(entity);
        return Response.ok().putData(true);
    }


    /**
     * 更新基本信息--居住信息
     *
     * @param userResident
     * @return
     */
    @Override
    public Response<Boolean> updateUserResident(UserResident userResident) {
        if (StringUtils.isBlank(userResident.getUserCode())) {
            return Response.error(UserErrorCodeEnum.LOST_USER_ID);
        }
        UserBaseResidentEntity entity = new UserBaseResidentEntity();
        BeanUtils.copyProperties(userResident, entity);
        entity.setGmtModified(new Date());
        userBaseResidentDao.updateByUserCode(entity);
        return Response.ok().putData(true);
    }

    /**
     * 更新基本信息--工作信息
     *
     * @param userWork
     * @return
     */
    @Override
    public Response<Boolean> updateUserWork(UserWork userWork) {
        if (StringUtils.isBlank(userWork.getUserCode())) {
            return Response.error(UserErrorCodeEnum.LOST_USER_ID);
        }
        UserBaseWorkEntity entity = new UserBaseWorkEntity();
        BeanUtils.copyProperties(userWork, entity);
        entity.setGmtModified(new Date());
        userBaseWorkDao.updateByUserCode(entity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<UserBase> getUserBase(String userCode) {
        UserBaseEntity userBaseEntity = userBaseDao.selectByUserCode(userCode);
        UserBase userBase = null;
        if (userBaseEntity != null) {
            userBase = new UserBase();
            BeanUtils.copyProperties(userBaseEntity, userBase);
        }
        return Response.ok().putData(userBase);
    }

    /**
     * 获取用户基本信息
     *
     * @param userCode
     * @return
     */
    @Override
    public Response<UserInfo> getUserInfoByUserCode(String userCode) {
        UserAccessEntity userAccess = userAccessDao.selectUserAccessByUserCode(userCode);
        if (userAccess == null) {
            return Response.ok().putData(new UserInfo());
        }

        String customerCode = userAccess.getCustomerCode();
        UserEntity customer = null;
        if (!StringUtils.isEmpty(customerCode)) {
            customer = userDao.selectByCustomerCode(customerCode);
        }

        UserEntity userEntity = new UserEntity().setUserCode(userCode)
                .setMobile(userAccess.getMobile());

        if (userAccess.getUserId() != null) {
            userEntity.setUserId(userAccess.getUserId().intValue());
        }

        if (customer != null) {
            userEntity.setName(customer.getName())
                    .setIdentityNo(customer.getIdentityNo())
                    .setUserType(customer.getUserType());
        }


        UserBaseEntity userBaseEntity = userBaseDao.selectByUserCode(userCode);
        UserBaseContactEntity userBaseContactEntity = userBaseContactDao.selectByUserCode(userCode);
        UserBaseResidentEntity userBaseResidentEntity = userBaseResidentDao.selectByUserCode(userCode);
        UserBaseWorkEntity userBaseWorkEntity = userBaseWorkDao.selectByUserCode(userCode);
        User user = null;
        if (userEntity != null) {
            user = new User();
            BeanUtils.copyProperties(userEntity, user);
            List<UserFrozen> frozenList = userFrozenService.getFrozenCode(userCode);
            if (frozenList != null) {
                user.setFrozenList(frozenList);
            }
        }

        UserBase userbase = null;
        if (userBaseEntity != null) {
            userbase = new UserBase();
            BeanUtils.copyProperties(userBaseEntity, userbase);
        }

        UserContact userContact = null;
        if (userBaseContactEntity != null) {
            userContact = new UserContact();
            BeanUtils.copyProperties(userBaseContactEntity, userContact);
        }

        UserResident userResident = null;
        if (userBaseResidentEntity != null) {
            userResident = new UserResident();
            BeanUtils.copyProperties(userBaseResidentEntity, userResident);
        }

        UserWork userWork = null;
        if (userBaseWorkEntity != null) {
            userWork = new UserWork();
            BeanUtils.copyProperties(userBaseWorkEntity, userWork);
        }

        UserInfo userInfo = new UserInfo(user, userbase, userContact, userResident, userWork);


        return Response.ok().putData(userInfo);
    }

    @Override
    public Response<Boolean> addUserPromotion(UserPromotion userPromotion) {
        LOGGER.info("== addUserPromotion  ==");
        try {
            UserPromotionStatsEntity promotionStats = new UserPromotionStatsEntity();
            promotionStats.setActionDate(userPromotion.getActionDate());
            promotionStats.setUserCode(userPromotion.getUserCode());
            promotionStats.setActionType(userPromotion.getActionType());
            promotionStats.setActionAccess(userPromotion.getActionAccess());
            promotionStats.setActionDate(new Date());
            userPromotionStatsDao.insert(promotionStats);
        } catch (Exception e) {
            LOGGER.info("== addUserPromotion  ==",e);

            e.printStackTrace();
        }
        return Response.ok().putData(true);
    }

    @Override
    public Response<UserResidentInfo> getUSerResidentInfoByUserCode(String userCode) {
        UserBaseResidentEntity entity = userBaseResidentDao.selectByUserCode(userCode);
        UserResidentInfo residentInfo = new UserResidentInfo();
        BeanUtils.copyProperties(entity, residentInfo);

        return Response.ok().putData(residentInfo);
    }

    @Override
    public Response<Boolean> addRiskBuriedPointInfo(List<UserBuriedData> userBuriedDataList, String userCode) {
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> addOperationFlow(String userCode, OperateTypeEnum operateTypeEnum) {
        UserOperateFlowEntity userOperateFlowEntity = new UserOperateFlowEntity();
        userOperateFlowEntity.setUserCode(userCode);
        userOperateFlowEntity.setType(operateTypeEnum.getType());
        userOperateFlowDao.insert(userOperateFlowEntity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> addOperationFlowV2(OperationFlow operationFlow) {
        if (StringUtils.isBlank(operationFlow.getUserCode())) {
            throw new ApiErrorException("userCode is empty");
        }
        if (operationFlow.getOperateTypeEnum() == null) {
            throw new ApiErrorException("operate type is empty");
        }

        UserOperateFlowEntity userOperateFlowEntity = new UserOperateFlowEntity();
        userOperateFlowEntity.setUserCode(operationFlow.getUserCode());
        userOperateFlowEntity.setType(operationFlow.getOperateTypeEnum().getType());
        userOperateFlowEntity.setExtInfo(operationFlow.getExtInfo());
        userOperateFlowDao.insert(userOperateFlowEntity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> searchOperationFlow(String userCode, OperateTypeEnum operateTypeEnum) {
        Map<String, Object> map = new HashMap<>();
        map.put("userCode", userCode);
        List<UserOperateFlowEntity> list = userOperateFlowDao.selectByParams(map);
        if (CollectionUtils.isEmpty(list)) {
            return Response.ok().putData(false);
        }
        return Response.ok().putData(true);
    }
}
